<?php

class ServiceController extends Core_Controller_Action {

    private function _detailaction() {
        $gi_id = $this->_getParam("giid");
        if (!Core_Util::hasAccessViewService($gi_id)) {
            $this->_handlePageNotFound();
            return;
        }
        if (empty($gi_id)) {
            $this->_handlePageNotFound();
        }

        $gi_db = new Core_Model_DbTable_GeneralInformation();
        $gi = $gi_db->getById($gi_id);

        if (empty($gi)) {
            $this->_handlePageNotFound();
        }

        $remittance_db = new Core_Model_DbTable_RemmitancesDetail();
        $this->view->remittances_detail = $remittance_db->getByGIID($gi_id);

        $ser_detail_db = new Core_Model_DbTable_ServicesDetail();
        $this->view->services_detail = $ser_detail_db->getByGIID($gi_id);

        $input_docs_db = new Core_Model_DbTable_InputDocs();
        $this->view->input_docs = $input_docs_db->getByGIID($gi_id);

//        $input_photo_db = new Core_Model_DbTable_InputPhotos();
//        $this->view->input_photos = $input_photo_db->getByGIID($gi_id);

        $folder_db = new Core_Model_DbTable_PhotoFolders();
        $this->view->folders = $folder_db->getFolders($gi_id);

        $doc_folder_db = new Core_Model_DbTable_DocumentFolders();
        $this->view->doc_folders = $doc_folder_db->getFolders($gi_id);
        
        $user_db = new Core_Model_DbTable_Users();
        $this->view->customer_name = $user_db->getFullName($gi->customer);

        $port_db = new Core_Model_DbTable_Ports();

        $buoy_db = new Core_Model_DbTable_Buoys();
        if ($gi->buoy > 0) {
            $buoy = $buoy_db->getDetail($gi->buoy);
            $this->view->buoy_name = $buoy->name;
        }

        if ($gi->port_of_call > 0) {
            $port_ids = array($gi->port_of_call);
            $ports = $port_db->getMulti($port_ids);
            $this->view->port_of_call_name = $ports[$gi->port_of_call]['name'];
        }
        $this->view->gi = $gi;
    }

    public function detailmobileAction() {
        $this->_helper->layout()->setLayout("layout_mobile");
        $this->_detailaction();
    }

    public function detailAction() {
        if ("mobile" == Core_MobileDetect::getCurrentDevice()) {
            $this->detailmobileAction();
            $this->render("detailmobile");
        } else {
            $this->_detailaction();
        }
    }

    public function profomaAction() {
        require_once LIB_PATH . '/html2pdf/html2pdf.class.php';
        $gi_id = $this->_getParam("giid");

        if (empty($gi_id)) {
            $this->_handlePageNotFound();
        }

        $gi_db = new Core_Model_DbTable_GeneralInformation();
        $gi = $gi_db->getById($gi_id);

        if (empty($gi)) {
            $this->_handlePageNotFound();
        }

        $this->view->gi = $gi;

        $ser_detail_db = new Core_Model_DbTable_ServicesDetail();
        $services_detail = $ser_detail_db->getByGIID($gi_id);
        $total_service = 0;
        foreach ($services_detail as $service_detail) {
            $total_service += $service_detail->amount;
        }
        $this->view->services_detail = $ser_detail_db->getByGIID($gi_id);
        $this->view->total_service_amount = $total_service;

        $user_db = new Core_Model_DbTable_Users();
        $this->view->customer_name = $user_db->getFullName($gi->customer);

        $port_db = new Core_Model_DbTable_Ports();
        $port_ids = array($gi->port_of_call);
        $ports = $port_db->getMulti($port_ids);
        $this->view->port_of_call_name = $ports[$gi->port_of_call]['name'];

        //$this->_helper->layout()->disableLayout();
        $this->setAjaxCall();
        $content = $this->view->render('/service/profoma.phtml');
        try {
            $html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8', array(20, 10, 0, 10));
            //$html2pdf->setModeDebug();
            $html2pdf->pdf->SetTitle("PDA-{$gi->ref_no}.pdf");
            $html2pdf->writeHTML($content);
            $html2pdf->Output("PDA-{$gi->ref_no}.pdf");
        } catch (HTML2PDF_exception $e) {
            if (Core_Util::isDebugMode()) {
                Zend_Debug::dump($e);
            }
            Core_Util::log($e);
        }
    }

    public function exportPdfAction() {
        require_once LIB_PATH . '/html2pdf/html2pdf.class.php';
        $gi_id = $this->_getParam("giid");

        if (empty($gi_id)) {
            $this->_handlePageNotFound();
        }

        $gi_db = new Core_Model_DbTable_GeneralInformation();
        $gi = $gi_db->getById($gi_id);

        if (empty($gi)) {
            $this->_handlePageNotFound();
        }

        $this->view->gi = $gi;

        $remittance_db = new Core_Model_DbTable_RemmitancesDetail();
        $this->view->remittances_detail = $remittance_db->getByGIID($gi_id);

        $ser_detail_db = new Core_Model_DbTable_ServicesDetail();
        $services_detail = $ser_detail_db->getByGIID($gi_id);
        $total_service = 0;
        foreach ($services_detail as $service_detail) {
            $total_service += $service_detail->amount;
        }
        $this->view->services_detail = $ser_detail_db->getByGIID($gi_id);
        $this->view->total_service_amount = $total_service;

        $input_docs_db = new Core_Model_DbTable_InputDocs();
        $this->view->input_docs = $input_docs_db->getByGIID($gi_id);
        $input_photo_db = new Core_Model_DbTable_InputPhotos();
        $this->view->input_photos = $input_photo_db->getByGIID($gi_id);

        $user_db = new Core_Model_DbTable_Users();
        $this->view->customer_name = $user_db->getFullName($gi->customer);

        $port_db = new Core_Model_DbTable_Ports();
        $port_ids = array($gi->port_of_call);
        $ports = $port_db->getMulti($port_ids);
        $this->view->port_of_call_name = $ports[$gi->port_of_call]['name'];

        //$this->_helper->layout()->disableLayout();
        $this->setAjaxCall();
        $content = $this->view->render('/service/export-pdf.phtml');
        try {
            $html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8', array(20, 10, 14, 10));
            //$html2pdf->setModeDebug();
            $html2pdf->pdf->SetTitle("TA-{$gi->ref_no}.pdf");
            $html2pdf->writeHTML($content);
            $html2pdf->Output("TA-{$gi->ref_no}.pdf");
        } catch (HTML2PDF_exception $e) {
            if (Core_Util::isDebugMode()) {
                Zend_Debug::dump($e);
            }
            Core_Util::log($e);
        }
        //$this->_helper->layout()->disableLayout();
    }

    public function excelTripAccountAction() {
        $gi_id = $this->_getParam("giid");

        if (empty($gi_id)) {
            $this->_handlePageNotFound();
        }

        $gi_db = new Core_Model_DbTable_GeneralInformation();
        $gi = $gi_db->getById($gi_id);

        if (empty($gi)) {
            $this->_handlePageNotFound();
        }

        $this->view->gi = $gi;

        $remittance_db = new Core_Model_DbTable_RemmitancesDetail();
        $this->view->remittances_detail = $remittance_db->getByGIID($gi_id);

        $ser_detail_db = new Core_Model_DbTable_ServicesDetail();
        $services_detail = $ser_detail_db->getByGIID($gi_id);
        $total_service = 0;
        foreach ($services_detail as $service_detail) {
            $total_service += $service_detail->amount;
        }
        $this->view->services_detail = $ser_detail_db->getByGIID($gi_id);
        $this->view->total_service_amount = $total_service;

        $input_docs_db = new Core_Model_DbTable_InputDocs();
        $this->view->input_docs = $input_docs_db->getByGIID($gi_id);
        $input_photo_db = new Core_Model_DbTable_InputPhotos();
        $this->view->input_photos = $input_photo_db->getByGIID($gi_id);

        $user_db = new Core_Model_DbTable_Users();
        $this->view->customer_name = $user_db->getFullName($gi->customer);

        $port_db = new Core_Model_DbTable_Ports();
        $port_ids = array($gi->port_of_call);
        $ports = $port_db->getMulti($port_ids);
        $this->view->port_of_call_name = $ports[$gi->port_of_call]['name'];

        $this->_helper->layout()->disableLayout();

        header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
        header("Content-Disposition: attachment; filename=TA-{$gi->ref_no}.xls");  //File name extension was wrong
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false);
    }

    public function cargoAction() {
        
    }

    public function dunnageAction() {
        
    }

    public function tallyAction() {
        
    }

    private function _getPurposeOfCall() {
        $purpose = new Core_Model_DbTable_Purposes();
        return $purpose->getAll();
    }

    private function _getCommodities() {
        return array(
            'Equipment', 'Bagged rice', 'Bulk',
            'Project', 'Steel', 'Oil product'
        );
    }

    private function _getUnits() {
        return array(
            'CBM', 'MT', 'bags', 'packages'
        );
    }

    private function _getCrewStatus() {
        return array(
            'Under clearance',
            'Safety on board',
            'Repatriated',
            "Visa granted and awaiting for crews arrival",
            "Crew on the way to the airport",
            "Crew on the way to the vessel"
        );
    }

    public function newAction() {
        if (!Core_Util::hasAccessNewService()) {
            $this->_handlePageNotFound();
            return;
        }
        if ($this->getRequest()->isPost()) {
            $ref_no = $this->_getParam("ref_no");
            $customer = $this->_getParam("customer_name");
            $vessel = $this->_getParam("vessel");
            $purpose_of_call = $this->_getParam("purpose_of_call");
            $port_of_call = $this->_getParam("port_of_call");
            $gtr = $this->_getParam("gtr");
            $buoy = $this->_getParam("buoy");
            $last_port_of_call = $this->_getParam("last_port_of_call");
            $next_port_of_call = $this->_getParam("next_port_of_call");
            $commodities = $this->_getParam("commodities");
            $quantity = $this->_getParam("quantity");
            $quantity_unit = $this->_getParam("quantity_unit");
            $voyage_no = $this->_getParam("voyage_no");
            $flag = $this->_getParam("flag");
            $eta = $this->_getTimestampParam("eta", '!d/m/Y H:i');
            $ata = $this->_getTimestampParam("ata", '!d/m/Y H:i');
            $etb = $this->_getTimestampParam("etb", '!d/m/Y H:i');
            $atb = $this->_getTimestampParam("atb", '!d/m/Y H:i');
            $ets = $this->_getTimestampParam("ets", '!d/m/Y H:i');
            $ats = $this->_getTimestampParam("ats", '!d/m/Y H:i');
            $upload_path = $this->getUploadDirectory($ref_no);
            $vessel_on_arrival = $this->uploadFile("vessel_on_arrival", $upload_path);
            $vessel_on_departure = $this->uploadFile("vessel_on_departure", $upload_path);
            $total_cargo_loaded_last_24h = $this->_getParam("total_cargo_loaded_last_24h");
            $total_cargo_loaded_uptodate = $this->_getParam("total_cargo_loaded_uptodate");
            $total_cargo_discharged_last_24h = $this->_getParam("total_cargo_discharged_last_24h");
            $total_cargo_discharged_uptodate = $this->_getParam("total_cargo_discharged_uptodate");
            $data = array(
                'ref_no' => $ref_no,
                'customer' => $customer,
                'attn' => $this->_getParam("attn"),
                'vessel' => $vessel,
                'purpose_of_call' => $purpose_of_call,
                'port_of_call' => $port_of_call,
                'gtr' => $gtr,
                'buoy' => $buoy,
                'last_port_of_call' => $last_port_of_call,
                'next_port_of_call' => $next_port_of_call,
                'commodities' => $commodities,
                'quantity' => $quantity,
                'quantity_unit' => $quantity_unit,
                'voyage_no' => $voyage_no,
                'flag' => $flag,
                'eta' => $eta,
                'ata' => $ata,
                'etb' => $etb,
                'atb' => $atb,
                'ets' => $ets,
                'ats' => $ats,
                'vessel_on_arrival' => $vessel_on_arrival,
                'vessel_on_departure' => $vessel_on_departure,
                'total_cargo_loaded_last_24h' => $total_cargo_loaded_last_24h,
                'total_cargo_loaded_uptodate' => $total_cargo_loaded_uptodate,
                'total_cargo_discharged_last_24h' => $total_cargo_discharged_last_24h,
                'total_cargo_discharged_uptodate' => $total_cargo_discharged_uptodate,
                'cargo_net_weight' => $this->_getParam("net_weight"),
                'cargo_gross_weight' => $this->_getParam("gross_weight"),
                'cargo_bags_no' => $this->_getParam("bags_no"),
                'commenced_cargo' => $this->_getTimestampParam("commenced_cargo", '!d/m/Y H:i'),
                'completed_cargo' => $this->_getTimestampParam("completed_cargo", '!d/m/Y H:i'),
                'tcll24h_unit' => $this->_getParam("tcll24h_unit"),
                'tclutd_unit' => $this->_getParam("tclutd_unit"),
                'tcdl24h_unit' => $this->_getParam("tcdl24h_unit"),
                'tcdutd_unit' => $this->_getParam("tcdutd_unit"),
                'updated_time' => time(),
                'on_signer_status' => $this->_getParam("on_signer_status"),
                'on_signer_status_date' => $this->_getTimestampParam('on_signer_status_date', '!d/m/Y H:i'),
                'off_signer_status' => $this->_getParam("off_signer_status"),
                'off_signer_status_date' => $this->_getTimestampParam('off_signer_status_date', '!d/m/Y H:i'),
                'commenced_dunnage' => $this->_getTimestampParam('commenced_dunnage', '!d/m/Y H:i'),
                'completed_dunnage' => $this->_getTimestampParam('completed_dunnage', '!d/m/Y H:i'),
                'net_weight_unit' => $this->_getParam("net_weight_unit"),
                'gross_weight_unit' => $this->_getParam("gross_weight_unit")
            );
            $general_information_db = new Core_Model_DbTable_GeneralInformation();
            $gi_id = $general_information_db->insert($data);
            $photos = $this->_getParam("photos");
            if (!empty($photos)) {
                $photo_db = new Core_Model_DbTable_InputPhotos();
                $index = 0;
                $photo_descs = $this->_getParam("photo_desc");
                foreach ($photos as $photo) {
                    $photo_data = array(
                        'gi_id' => $gi_id,
                        'created_time' => time(),
                        'file' => $photo,
                        'description' => $photo_descs[$index++]
                    );
                    $photo_db->insert($photo_data);
                }
            }
            $documents = $this->_getParam("documents");
            if (!empty($documents)) {
                $doc_db = new Core_Model_DbTable_InputDocs();
                foreach ($documents as $document) {
                    $doc_data = array(
                        'gi_id' => $gi_id,
                        'created_time' => time(),
                        'file' => $document
                    );
                    $doc_db->insert($doc_data);
                }
            }

            $rem_customers = $this->_getParam("rem_customers");
            $rem_dates = $this->_getParam("rem_dates");
            $rem_amounts = $this->_getParam("rem_amounts");
            $rem_remarks = $this->_getParam("rem_remarks");
            if (!empty($rem_customers)) {
                $rem_detail_db = new Core_Model_DbTable_RemmitancesDetail();
                for ($i = 0; $i < sizeof($rem_customers); $i++) {
                    $remmitance_data = array(
                        'gi_id' => $gi_id,
                        'amount' => $rem_amounts[$i],
                        'customer' => $rem_customers[$i],
                        'remarks' => $rem_remarks[$i],
                        'date' => Core_Util::getTimestamp($rem_dates[$i])
                    );
                    $rem_detail_db->insert($remmitance_data);
                }
            }

            $ser_services = $this->_getParam("ser_services");
            if (!empty($ser_services)) {
                $ser_vouchers = $this->_getParam("ser_vouchers");
                $ser_amounts = $this->_getParam("ser_amounts");
                $ser_remarks = $this->_getParam("ser_remarks");
                $ser_detail_db = new Core_Model_DbTable_ServicesDetail();
                for ($i = 0; $i < sizeof($ser_services); $i++) {
                    $service_detail = array(
                        'gi_id' => $gi_id,
                        'amount' => $ser_amounts[$i],
                        'voucher' => $ser_vouchers[$i],
                        'remarks' => $ser_remarks[$i],
                        'service' => $ser_services[$i]
                    );
                    $ser_detail_db->insert($service_detail);
                }
            }
            $general_information_db->setUsedTrackingInput($ref_no);
            $this->session->ref_no = NULL;
            $this->_redirect("tracking");
        } else {
            $user_db = new Core_Model_DbTable_Users();
            $this->view->customers = $user_db->getCustomers();

            $session = $this->session;
            if (!$session->ref_no) {
                $gi_db = new Core_Model_DbTable_GeneralInformation();
                $ref_no = $gi_db->generateRefNo();
                $this->view->ref_no = $ref_no;
                $session->ref_no = $ref_no;
            } else {
                $this->view->ref_no = $session->ref_no;
            }

            $port_db = new Core_Model_DbTable_Ports();
            $this->view->ports = $port_db->getAll();
            $buoy_db = new Core_Model_DbTable_Buoys();
            $this->view->buoys = $buoy_db->getAll();
            $this->view->purpose_of_calls = $this->_getPurposeOfCall();
            $this->view->commodities = $this->_getCommodities();
            $this->view->units = $this->_getUnits();
            $service_db = new Core_Model_DbTable_Services();
            $this->view->services = $service_db->getAll();
            $this->view->countries = Core_Util::getCountryList();
            $signersatus_db = new Core_Model_DbTable_SignerStatus();
            $this->view->crew_statuses = $signersatus_db->getAll();
        }
    }

    public function updateAction() {
        if (!Core_Util::hasAccessNewService()) {
            $this->_handlePageNotFound();
            return;
        }
        $gi_id = $this->_getParam("giid");
        $gi_db = new Core_Model_DbTable_GeneralInformation();
        $gi = $gi_db->getById($gi_id);
        if (empty($gi)) {
            $this->_handlePageNotFound();
        }
        if ($this->getRequest()->isPost()) {
            //general information
            $ref_no = $this->_getParam("ref_no");
            $customer = $this->_getParam("customer_name");
            $vessel = $this->_getParam("vessel");
            $purpose_of_call = $this->_getParam("purpose_of_call");
            $port_of_call = $this->_getParam("port_of_call");
            $gtr = $this->_getParam("gtr");
            $buoy = $this->_getParam("buoy");
            $last_port_of_call = $this->_getParam("last_port_of_call");
            $next_port_of_call = $this->_getParam("next_port_of_call");
            $commodities = $this->_getParam("commodities");
            $quantity = $this->_getParam("quantity");
            $quantity_unit = $this->_getParam("quantity_unit");
            $voyage_no = $this->_getParam("voyage_no");
            $flag = $this->_getParam("flag");
            $eta = $this->_getTimestampParam("eta", '!d/m/Y H:i');
            $ata = $this->_getTimestampParam("ata", '!d/m/Y H:i');
            $etb = $this->_getTimestampParam("etb", '!d/m/Y H:i');
            $atb = $this->_getTimestampParam("atb", '!d/m/Y H:i');
            $ets = $this->_getTimestampParam("ets", '!d/m/Y H:i');
            $ats = $this->_getTimestampParam("ats", '!d/m/Y H:i');
            $upload_path = $this->getUploadDirectory($ref_no);
            $vessel_on_arrival = $this->uploadFile("vessel_on_arrival", $upload_path);
            $vessel_on_departure = $this->uploadFile("vessel_on_departure", $upload_path);
            $total_cargo_loaded_last_24h = $this->_getParam("total_cargo_loaded_last_24h");
            $total_cargo_loaded_uptodate = $this->_getParam("total_cargo_loaded_uptodate");
            $total_cargo_discharged_last_24h = $this->_getParam("total_cargo_discharged_last_24h");
            $total_cargo_discharged_uptodate = $this->_getParam("total_cargo_discharged_uptodate");
            $data = array(
                'customer' => $customer,
                'attn' => $this->_getParam("attn"),
                'vessel' => $vessel,
                'purpose_of_call' => $purpose_of_call,
                'port_of_call' => $port_of_call,
                'gtr' => $gtr,
                'buoy' => $buoy,
                'last_port_of_call' => $last_port_of_call,
                'next_port_of_call' => $next_port_of_call,
                'commodities' => $commodities,
                'quantity' => $quantity,
                'quantity_unit' => $quantity_unit,
                'voyage_no' => $voyage_no,
                'flag' => $flag,
                'eta' => $eta,
                'ata' => $ata,
                'etb' => $etb,
                'atb' => $atb,
                'ets' => $ets,
                'ats' => $ats,
                'total_cargo_loaded_last_24h' => $total_cargo_loaded_last_24h,
                'total_cargo_loaded_uptodate' => $total_cargo_loaded_uptodate,
                'total_cargo_discharged_last_24h' => $total_cargo_discharged_last_24h,
                'total_cargo_discharged_uptodate' => $total_cargo_discharged_uptodate,
                'cargo_net_weight' => $this->_getParam("net_weight"),
                'cargo_gross_weight' => $this->_getParam("gross_weight"),
                'cargo_bags_no' => $this->_getParam("bags_no"),
                'commenced_cargo' => $this->_getTimestampParam("commenced_cargo", '!d/m/Y H:i'),
                'completed_cargo' => $this->_getTimestampParam("completed_cargo", '!d/m/Y H:i'),
                'tcll24h_unit' => $this->_getParam("tcll24h_unit"),
                'tclutd_unit' => $this->_getParam("tclutd_unit"),
                'tcdl24h_unit' => $this->_getParam("tcdl24h_unit"),
                'tcdutd_unit' => $this->_getParam("tcdutd_unit"),
                'on_signer_status' => $this->_getParam("on_signer_status"),
                'on_signer_status_date' => $this->_getTimestampParam('on_signer_status_date', '!d/m/Y H:i'),
                'off_signer_status' => $this->_getParam("off_signer_status"),
                'off_signer_status_date' => $this->_getTimestampParam('off_signer_status_date', '!d/m/Y H:i'),
                'commenced_dunnage' => $this->_getTimestampParam('commenced_dunnage', '!d/m/Y H:i'),
                'completed_dunnage' => $this->_getTimestampParam('completed_dunnage', '!d/m/Y H:i'),
                'net_weight_unit' => $this->_getParam("net_weight_unit"),
                'gross_weight_unit' => $this->_getParam("gross_weight_unit")
            );
            if (!empty($vessel_on_arrival)) {
                $data['vessel_on_arrival'] = $vessel_on_arrival;
            }
            if (!empty($vessel_on_departure)) {
                $data['vessel_on_departure'] = $vessel_on_departure;
            }

            //documents
            $documents = $this->_getParam("documents");
            if (!empty($documents)) {
                $doc_db = new Core_Model_DbTable_InputDocs();
                foreach ($documents as $document) {
                    $doc_data = array(
                        'gi_id' => $gi_id,
                        'created_time' => time(),
                        'file' => $document
                    );
                    $doc_db->insert($doc_data);
                }
            }

            //remittances
            $rem_customers = $this->_getParam("rem_customers");
            $rem_dates = $this->_getParam("rem_dates");
            $rem_amounts = $this->_getParam("rem_amounts");
            $rem_remarks = $this->_getParam("rem_remarks");
            if (!empty($rem_customers)) {
                $rem_detail_db = new Core_Model_DbTable_RemmitancesDetail();
                for ($i = 0; $i < sizeof($rem_customers); $i++) {
                    $remmitance_data = array(
                        'gi_id' => $gi_id,
                        'amount' => $rem_amounts[$i],
                        'customer' => $rem_customers[$i],
                        'date' => Core_Util::getTimestamp($rem_dates[$i]),
                        'remarks' => $rem_remarks[$i]
                    );
                    $rem_detail_db->insert($remmitance_data);
                }
            }

            //services
            $ser_services = $this->_getParam("ser_services");
            if (!empty($ser_services)) {
                $ser_vouchers = $this->_getParam("ser_vouchers");
                $ser_amounts = $this->_getParam("ser_amounts");
                $ser_remarks = $this->_getParam("ser_remarks");
                $ser_detail_db = new Core_Model_DbTable_ServicesDetail();
                $is_news = $this->_getParam("is_new");
                $ser_detail_ids = $this->_getParam("ser_detail_id");
                for ($i = 0; $i < sizeof($ser_services); $i++) {
                    $service_detail = array(
                        'gi_id' => $gi_id,
                        'amount' => $ser_amounts[$i],
                        'voucher' => $ser_vouchers[$i],
                        'remarks' => $ser_remarks[$i],
                        'service' => $ser_services[$i]
                    );
                    if ($is_news[$i] == 1) {
                        $ser_detail_db->insert($service_detail);
                        $data['updated_time'] = time();
                    } else {
                        $cond = $ser_detail_db->getAdapter()->quoteInto("id = (?)", $ser_detail_ids[$i]);
                        $old_service = $ser_detail_db->fetchRow($cond);
                        if ($old_service['amount'] != $service_detail['amount'] || $old_service['voucher'] != $service_detail['voucher'] || $old_service['service'] != $service_detail['service'] || $old_service['remarks'] != $service_detail['remarks']) {
                            $ser_detail_db->update($service_detail, $cond);
                            $data['updated_time'] = time();
                        }
                    }
                }
            }

            $general_information_db = new Core_Model_DbTable_GeneralInformation();
            $general_information_db->update($data, "id = $gi_id");
            $this->_redirect("tracking");
        } else {
            $gi_id = $this->_getParam("giid");
            $gi_db = new Core_Model_DbTable_GeneralInformation();
            $gi = $gi_db->getById($gi_id);
            if (empty($gi)) {
                $this->_handlePageNotFound();
            }
            $this->view->gi = $gi;

            $user_db = new Core_Model_DbTable_Users();
            $this->view->customers = $user_db->getCustomers();
            $port_db = new Core_Model_DbTable_Ports();
            $this->view->ports = $port_db->getAll();
            $buoy_db = new Core_Model_DbTable_Buoys();
            $this->view->buoys = $buoy_db->getAll();
            $this->view->purpose_of_calls = $this->_getPurposeOfCall();
            $this->view->commodities = $this->_getCommodities();
            $this->view->units = $this->_getUnits();
            $input_docs_db = new Core_Model_DbTable_InputDocs();
            $this->view->input_docs = $input_docs_db->getByGIID($gi_id);

//            $input_photo_db = new Core_Model_DbTable_InputPhotos();
//            $this->view->input_photos = $input_photo_db->getByGIID($gi_id);

            $folder_db = new Core_Model_DbTable_PhotoFolders();
            $this->view->folders = $folder_db->getFolders($gi_id);

            $doc_folder_db = new Core_Model_DbTable_DocumentFolders();
            $this->view->doc_folders = $doc_folder_db->getFolders($gi_id);
            
            $remittance_db = new Core_Model_DbTable_RemmitancesDetail();
            $this->view->remittances_detail = $remittance_db->getByGIID($gi_id);

            $ser_detail_db = new Core_Model_DbTable_ServicesDetail();
            $this->view->services_detail = $ser_detail_db->getByGIID($gi_id);

            $services_db = new Core_Model_DbTable_Services();
            $this->view->services = $services_db->getAll();
            $this->view->countries = Core_Util::getCountryList();
            $signerstatus_db = new Core_Model_DbTable_SignerStatus();
            $this->view->crew_statuses = $signerstatus_db->getAll();
        }
    }

    public function getbuoysAction() {
        $this->setAjaxCall();

        $buoy_db = new Core_Model_DbTable_Buoys();
        $port_id = $this->_getParam("pid");
        if (!empty($port_id)) {
            $buoys = $buoy_db->getBuoyByPort($port_id);
            echo json_encode($buoys->toArray());
        } else {
            echo json_encode(array());
        }
    }

    public function pluploadAction() {

        $this->setAjaxCall();

        $id = $this->_getParam("id");
        // Settings
        $targetDir = $this->getUploadDirectory($id);
        //$targetDir = 'uploads';

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
        // 5 minutes execution time
        @set_time_limit(5 * 60);

        // Uncomment this one to fake upload time
        // usleep(5000);
        // Get parameters
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
        $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';

        // Clean the fileName for security reasons
        $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);

        // Make sure the fileName is unique but only if chunking is disabled
        if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
            $ext = strrpos($fileName, '.');
            $fileName_a = substr($fileName, 0, $ext);
            $fileName_b = substr($fileName, $ext);

            $count = 1;
            while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
                $count++;

            $fileName = $fileName_a . '_' . $count . $fileName_b;
        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

        // Create target dir
        if (!file_exists($targetDir))
            @mkdir($targetDir);

        // Remove old temp files	
        if ($cleanupTargetDir) {
            if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
                while (($file = readdir($dir)) !== false) {
                    $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                    // Remove temp file if it is older than the max age and is not the current file
                    if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) {
                        @unlink($tmpfilePath);
                    }
                }
                closedir($dir);
            } else {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }
        }

        // Look for the content type header
        if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
            $contentType = $_SERVER["HTTP_CONTENT_TYPE"];

        if (isset($_SERVER["CONTENT_TYPE"]))
            $contentType = $_SERVER["CONTENT_TYPE"];

        // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
        if (strpos($contentType, "multipart") !== false) {
            if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                // Open temp file
                $out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
                if ($out) {
                    // Read binary input stream and append it to temp file
                    $in = @fopen($_FILES['file']['tmp_name'], "rb");

                    if ($in) {
                        while ($buff = fread($in, 4096))
                            fwrite($out, $buff);
                    }
                    else
                        die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                    @fclose($in);
                    @fclose($out);
                    @unlink($_FILES['file']['tmp_name']);
                }
                else
                    die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }
            else
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
        } else {
            // Open temp file
            $out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
            if ($out) {
                // Read binary input stream and append it to temp file
                $in = @fopen("php://input", "rb");

                if ($in) {
                    while ($buff = fread($in, 4096))
                        fwrite($out, $buff);
                }
                else
                    die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');

                @fclose($in);
                @fclose($out);
            }
            else
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        // Check if file has been uploaded
        if (!$chunks || $chunk == $chunks - 1) {
            // Strip the temp .part suffix off 
            rename("{$filePath}.part", $filePath);
        }
        Core_Util::scaleImage($filePath, $filePath, 75);
        $relative_file_path = str_replace(UPLOAD_PATH, "", $filePath);
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id", "path": "' . $relative_file_path . '", "file_name": "' . $fileName . '"}');
    }

    private function getUploadDirectory($id) {
        $year = date('Y');
        $month = date('m');
        $day = date('d');
        $upload_path = UPLOAD_PATH . $year;
        if (!file_exists($upload_path)) {
            mkdir($upload_path);
        }
        $upload_path .= DIRECTORY_SEPARATOR . $month;
        if (!file_exists($upload_path)) {
            mkdir($upload_path);
        }

        $upload_path .= DIRECTORY_SEPARATOR . $day;
        if (!file_exists($upload_path)) {
            mkdir($upload_path);
        }

        $upload_path .= DIRECTORY_SEPARATOR . $id;
        if (!file_exists($upload_path)) {
            mkdir($upload_path);
        }

        return $upload_path;
    }

    public function deleteUploadFileAction() {
        $this->setAjaxCall();

        $file_name = $this->_getParam("file_name");
        if (empty($file_name)) {
            return;
        }
        $id = $this->_getParam("id");
        if ($id) {
            $service_type = $this->_getParam("service_type");
            if ($service_type) {
                $class_name = "Core_Model_DbTable_Input" . $service_type;
                $cargo_documents_db = new $class_name();
                $cargo_documents_db->delete("id = $id");
            }
        }
        $full_file_name = UPLOAD_PATH . $file_name;
        unlink($full_file_name);
    }

    protected function _getParam($paramName, $default = null, $quote = true) {
        $value = parent::_getParam($paramName, $default);
        if (empty($value) && $default === NULL) {
            return NULL;
        } else {
            if ($quote) {
                if (!is_array($value)) {
                    $value = htmlspecialchars($value);
                }
            }
            return $value;
        }
    }

    public function deletevesselonarrivalAction() {
        $this->setAjaxCall();
        $id = $this->_getParam("id");
        if (!$id) {
            echo json_encode(false);
        } else {
            $gen = new Core_Model_DbTable_GeneralInformation();
            $gen->update(array("vessel_on_arrival" => ""), $gen->getAdapter()->quoteInto("id = (?)", $id));
            echo json_encode(true);
        }
    }

    public function deletevesselondepartureAction() {
        $this->setAjaxCall();
        $id = $this->_getParam("id");
        if (!$id || !$this->getRequest()->isPost()) {
            $this->_handlePageNotFound();
            echo json_encode(false);
        } else {
            $gen = new Core_Model_DbTable_GeneralInformation();
            $gen->update(array("vessel_on_departure" => ""), $gen->getAdapter()->quoteInto("id = (?)", $id));
            echo json_encode(true);
        }
    }

    public function deleteUpdateDunnageOperationAction() {
        $this->setAjaxCall();

        if ($this->getRequest()->isPost()) {
            $update_dunnage_id = $this->_getParam("id");
            if (!empty($update_dunnage_id)) {
                $update_dunnage_operation_db = new Core_Model_DbTable_UpdateDunnageOperations();
                echo $update_dunnage_operation_db->deleteById($update_dunnage_id);
            }
        } else {
            $this->_handlePageNotFound();
        }
    }

    public function deleteRemittanceAction() {
        $this->setAjaxCall();

        if ($this->getRequest()->isPost()) {
            $id = $this->_getParam("id");
            if (empty($id)) {
                exit(0);
            } else {
                $rem_db = new Core_Model_DbTable_RemmitancesDetail();
                $rem_db->delete("id = $id");
            }
        }
    }

    public function deleteServiceDetailAction() {
        $this->setAjaxCall();

        if ($this->getRequest()->isPost()) {
            $id = $this->_getParam("id");
            if (empty($id)) {
                exit(0);
            } else {
                $ser_db = new Core_Model_DbTable_ServicesDetail();
                $ser_db->delete("id = $id");
            }
        }
    }

    public function addFolderAction() {
        $this->_helper->layout()->disableLayout();
        $gi_id = $this->_getParam("gi_id");
        $type = $this->_getParam("type", 'folder');
        $this->view->gi_id = $gi_id;
        $this->view->type = $type;

        if ($this->getRequest()->isPost()) {
            $folder_name = $this->_getParam("name");
            $data = array(
                'name' => $folder_name,
                'gi_id' => $gi_id,
                'created_time' => time()
            );
            $fid = $this->_getParam("fid");
            if ($type == 'folder') {
                $folder_db = new Core_Model_DbTable_PhotoFolders();
            } else {
                $folder_db = new Core_Model_DbTable_DocumentFolders();
            }
            if (!$fid) {
                $folder_db->insert($data);
            } else {
                $folder_db->update($data, "id = $fid");
                $urlOptions = array('controller' => 'service', 'action' => 'update', 'giid' => $gi_id);
                $this->_helper->redirector->gotoRoute($urlOptions);
            }
        }
    }

    public function addPhotoAction() {
        $this->_helper->layout()->disableLayout();

        $gi_id = $this->_getParam("gi_id");
        $ref_no = $this->_getParam("ref_no");

        if (!$gi_id || !$ref_no) {
            exit(0);
        }
        $this->view->gi_id = $gi_id;
        $this->view->ref_no = $ref_no;

        $photo_folder_db = new Core_Model_DbTable_PhotoFolders();
        $this->view->folders = $photo_folder_db->getFolders($gi_id);

        if ($this->getRequest()->isPost()) {
            $upload_path = $this->getUploadDirectory($ref_no);
            $photo = $this->uploadFile('photo', $upload_path);
            $description = $this->_getParam("description");
            $folder_id = $this->_getParam("folder");
            $data = array(
                'gi_id' => $gi_id,
                'file' => $photo,
                'description' => $description,
                'folder' => $folder_id,
                'created_time' => time()
            );
            $input_photos_db = new Core_Model_DbTable_InputPhotos();
            $input_photos_db->insert($data);
            $urlOptions = array('controller' => 'service', 'action' => 'update', 'giid' => $gi_id);
            $this->_helper->redirector->gotoRoute($urlOptions);
        }
    }
    
    public function addDocAction() {
        $this->_helper->layout()->disableLayout();

        $gi_id = $this->_getParam("gi_id");
        $ref_no = $this->_getParam("ref_no");

        if (!$gi_id || !$ref_no) {
            exit(0);
        }
        $this->view->gi_id = $gi_id;
        $this->view->ref_no = $ref_no;

        $photo_folder_db = new Core_Model_DbTable_DocumentFolders();
        $this->view->folders = $photo_folder_db->getFolders($gi_id);

        if ($this->getRequest()->isPost()) {
            $upload_path = $this->getUploadDirectory($ref_no);
            $doc = $this->uploadFile('doc', $upload_path);
            $folder_id = $this->_getParam("folder");
            $data = array(
                'gi_id' => $gi_id,
                'file' => $doc,
                'folder' => $folder_id,
                'created_time' => time()
            );
            $input_photos_db = new Core_Model_DbTable_InputDocs();
            $input_photos_db->insert($data);
            $urlOptions = array('controller' => 'service', 'action' => 'update', 'giid' => $gi_id);
            $this->_helper->redirector->gotoRoute($urlOptions);
        }
    }

    public function showUpdateFolderPhotoAction() {
        $this->_helper->layout()->disableLayout();
        $folderId = $this->_getParam("fid");

        if (!$folderId) {
            exit(0);
        }

        $folder_db = new Core_Model_DbTable_PhotoFolders();
        $folder = $folder_db->getByPK($folderId);

        if (!$folder) {
            exit(0);
        }
        $this->view->folder = $folder;
        $photo_db = new Core_Model_DbTable_InputPhotos();
        $this->view->photos = $photo_db->getByFolder($folderId);
    }
    
    public function showUpdateFolderDocAction() {
        $this->_helper->layout()->disableLayout();
        $folderId = $this->_getParam("fid");

        if (!$folderId) {
            exit(0);
        }

        $folder_db = new Core_Model_DbTable_DocumentFolders();
        $folder = $folder_db->getByPK($folderId);

        if (!$folder) {
            exit(0);
        }
        $this->view->folder = $folder;
        $doc_db = new Core_Model_DbTable_InputDocs();
        $this->view->docs = $doc_db->getByFolder($folderId);
    }

    public function deletePhotoFolderAction() {
        if ($this->getRequest()->isPost()) {
            $this->setAjaxCall();
            $fid = $this->_getParam("fid");
            if (!$fid) {
                exit(0);
            }
            $photo_db = new Core_Model_DbTable_InputPhotos();
            $photo_db->deleteByFolder($fid);

            $photo_folder_db = new Core_Model_DbTable_PhotoFolders();
            $photo_folder_db->delete("id = $fid");
        }
        exit(0);
    }
    
    public function deleteDocumentFolderAction() {
        if ($this->getRequest()->isPost()) {
            $this->setAjaxCall();
            $fid = $this->_getParam("fid");
            if (!$fid) {
                exit(0);
            }
            $doc_db = new Core_Model_DbTable_InputDocs();
            $doc_db->deleteByFolder($fid);

            $photo_folder_db = new Core_Model_DbTable_DocumentFolders();
            $photo_folder_db->delete("id = $fid");
        }
        exit(0);
    }

    public function updatePhotosAction() {
        $gi_id = $this->_getParam("gi_id");
        $photo_db = new Core_Model_DbTable_InputPhotos();
        $photo_descs = $this->_getParam("photo_desc");
        $ids = $this->_getParam("photo_ids");
        $index = 0;
        foreach ($photo_descs as $index => $photo_desc) {
            $photo_data = array(
                'description' => $photo_desc
            );
            $photo_db->update($photo_data, "id = {$ids[$index]}");
        }
        $urlOptions = array('controller' => 'service', 'action' => 'update', 'giid' => $gi_id);
        $this->_helper->redirector->gotoRoute($urlOptions);
    }

    public function disbursementAction() {
        $giid = $this->_getParam("giid");
        $service_id = array($this->_getParam("sids"));

        if (!$giid || !$service_id) {
            $this->_handlePageNotFound();
        }

        $gi_db = new Core_Model_DbTable_GeneralInformation();
        $service_db = new Core_Model_DbTable_ServicesDetail();

        $gi = $gi_db->getById($giid);
        $service = $service_db->get($service_id);
        $user_db = new Core_Model_DbTable_Users();
        $this->view->customer_name = $user_db->getFullName($gi->customer);

        $port_db = new Core_Model_DbTable_Ports();
        if ($gi->port_of_call) {
            $port_of_call = $port_db->get($gi->port_of_call);
            $this->view->port_of_call_name = $port_of_call->name;
        }

        $user_id = $this->session->user->id;
        $tracking_invoice_db = new Core_Model_DbTable_TrackingInvoice();
        $invoice_number = $tracking_invoice_db->getInvoiceNumber($user_id);
        $this->view->invoice_number = $invoice_number;
        $this->view->gi = $gi;
        $this->view->services = $service;

        require_once LIB_PATH . '/html2pdf/html2pdf.class.php';
        $this->setAjaxCall();
        $content = $this->view->render('/service/disbursement.phtml');
        try {
            $html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8', array(20, 10, 14, 10));
            $html2pdf->pdf->SetTitle("INV-{$invoice_number}.pdf");
            $html2pdf->writeHTML($content);
            $html2pdf->Output("INV-{$invoice_number}.pdf");
        } catch (HTML2PDF_exception $e) {
            if (Core_Util::isDebugMode()) {
                Zend_Debug::dump($e);
            }
            Core_Util::log($e);
        }
    }

    public function showFolderPhotoAction() {
        $this->_helper->layout()->disableLayout();
        $folderId = $this->_getParam("fid");

        if (!$folderId) {
            exit(0);
        }

        $folder_db = new Core_Model_DbTable_PhotoFolders();
        $folder = $folder_db->getByPK($folderId);

        if (!$folder) {
            exit(0);
        }

        $photo_db = new Core_Model_DbTable_InputPhotos();
        $this->view->photos = $photo_db->getByFolder($folderId);
    }
    
    public function showFolderDocAction() {
        $this->_helper->layout()->disableLayout();
        $folderId = $this->_getParam("fid");

        if (!$folderId) {
            exit(0);
        }

        $folder_db = new Core_Model_DbTable_DocumentFolders();
        $folder = $folder_db->getByPK($folderId);

        if (!$folder) {
            exit(0);
        }

        $photo_db = new Core_Model_DbTable_InputDocs();
        $this->view->docs = $photo_db->getByFolder($folderId);
    }

}

?>
